//
//  MineViewController.m
//  JiuJiuShangCheng
//
//  Created by jiujiukeji on 2018/7/3.
//  Copyright © 2018年 jiujiukeji. All rights reserved.
//

#import "MineViewController.h"
#import "MineHeaderView.h"
#import "MineAccountItem.h"
#import "MineOrderItem.h"
#import "MineTableViewCell.h"
#import "OrderViewController.h"
#import "SettingViewController.h"
#import "NotificationViewController.h"
#import "MessageViewController.h"
#import "CollectionViewController.h"
#import "AddressViewController.h"
#import "PersonalInfoViewController.h"
#import "JiFenOrderViewController.h"
#import "MyJiFenViewController.h"
#import "TuiKuanViewController.h"
#import "AccountViewController.h"
#import "PersonalInfoViewController.h"
#import "CouponsViewController.h"
#import "LoginViewController.h"
#import "MyPingJiaViewController.h"

@interface MineViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSDictionary *personalInfoDic;
@property (nonatomic, strong) NSDictionary *orderNumDic;

@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = tableViewBgColor;
    
    [self.view addSubview:self.tableView];
    [self getPersonalInfo];
    [self getOrderNum];
    
    // 退出登录注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getResault) name:@"quitAction" object:nil];
}
- (void)getResault
{
    self.orderNumDic = nil;
    self.personalInfoDic = nil;
    [self.tableView reloadData];
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"quitAction" object:nil];
}
#pragma mark - 获取订单数量
- (void)getOrderNum
{
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/order.ashx?action=ordercount&companyid=%@&code=%@&timestamp=%@&type=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],@"1"] parameters:nil success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        [self.tableView.mj_header endRefreshing];
        if ([[NSString stringWithFormat:@"%@",responseObject[@"status"]] intValue] == 1) {
            self.orderNumDic = responseObject;
            [self.tableView reloadData];
        } else {
            [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
        }
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        [self.tableView.mj_header endRefreshing];
    }];
}
#pragma mark - 获取个人信息
- (void)getPersonalInfo
{
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=memberinfo&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:nil success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        [self.tableView.mj_header endRefreshing];
        NSLog(@"responseObject---%@",responseObject);
        if ([responseObject[@"status"] intValue] == 1) {
            self.personalInfoDic = responseObject;
            [self.tableView reloadData];
        } else {
            //            [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
        }
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        NSLog(@"error---%@",error);
        [self.tableView.mj_header endRefreshing];
    }];
}
- (void)setNavBar
{
    [self loadBaseTitleLable:@""];
    self.navTitleBgView.backgroundColor = [navBarColor colorWithAlphaComponent:0];
    self.leftBtn.hidden = YES;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    //    [self getPersonalInfo];
}
#pragma mark - 签到
- (void)signIn
{
    NSLog(@"123");
    if ([[UserDefaults valueForKey:@"isLogin"] intValue] == 0) {
        // 未登录
        [self loginAction];
    } else {
        NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
        [MBProgressHUD showMessage:nil toView:self.view];
        [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=signin&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:nil success:^(id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
            if ([responseObject[@"status"] intValue] == 1) {
                
            } else {
                
            }
            
        } failure:^(NSError *error) {
            [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
            
        }];
    }
    
}
#pragma mark - 设置
- (void)actionSetting
{
    NSLog(@"11111111111111111111");
    if ([[UserDefaults valueForKey:@"isLogin"] intValue] == 0) {
        // 未登录
        [self loginAction];
    } else {
        SettingViewController *settingVC = [[SettingViewController alloc] init];
        [self.navigationController pushViewController:settingVC animated:YES];
    }
    
}
#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 5;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 4) {
        return 8;
    } else {
        return 1;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 4) {
        MineTableViewCell *cell = [[MineTableViewCell alloc] init];
        NSArray *array1 = @[@"商品评价",@"优惠券",@"积分订单",@"个人资料",@"收货地址",@"我的收藏",@"我的消息",@"站内通知"];
        NSArray *array2 = @[@"mypingjia",@"tuangou",@"tuangou",@"gerenziliao",@"shouhuodizhi",@"wodeshoucang",@"wodexiaoxi",@"huiyuantongzhi"];
        cell.iconImg.image = UIImageNamed(array2[indexPath.row]);
        cell.titleLB.text = array1[indexPath.row];
        
        cell.selectionStyle = NO;
        return cell;
    } else {
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        if (indexPath.section == 0) {
            MineHeaderView *topV = [[MineHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, rateWidth(300))];
            [topV.rightBtn addTarget:self action:@selector(actionSetting) forControlEvents:(UIControlEventTouchUpInside)];
            [cell.contentView addSubview:topV];
            // 签到
            [topV.signBtn addTarget:self action:@selector(signIn) forControlEvents:(UIControlEventTouchUpInside)];
            
            if ([[UserDefaults valueForKey:@"isLogin"] intValue] == 0) {
                // 未登录
                topV.gradeImg.hidden = YES;
                topV.gradeLB.hidden = YES;
                topV.nameLB.text = @"登录/注册";
                // 跳转登录
                topV.nameLB.userInteractionEnabled = YES;
                UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(loginAction)];
                [topV.nameLB addGestureRecognizer:tap1];
                topV.headerImg.userInteractionEnabled = YES;
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(loginAction)];
                [topV.headerImg addGestureRecognizer:tap];
            } else {
                // 头像跳转个人资料
                topV.headerImg.userInteractionEnabled = YES;
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(personalInfoAction)];
                [topV.headerImg addGestureRecognizer:tap];
                
                // 赋值
                if ([[self.personalInfoDic[@"memberImg"] substringToIndex:5] isEqualToString:@"http:"]) {
                    [topV.headerImg sd_setImageWithURL:[NSURL URLWithString:self.personalInfoDic[@"memberImg"]]];
                } else {
                    [topV.headerImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http:%@",self.personalInfoDic[@"memberImg"]]]];
                }
                topV.nameLB.text = self.personalInfoDic[@"memberName"];
                topV.gradeLB.text = self.personalInfoDic[@"level"];
            }
            
        } else if (indexPath.section == 1) {
            MineAccountItem *accountV = [[MineAccountItem alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, rateWidth(120))];
            [cell.contentView addSubview:accountV];
            // 赋值
            accountV.btn1.topLB.text = self.personalInfoDic[@"integration"];
            accountV.btn2.topLB.text = self.personalInfoDic[@"ZMoney"];
            accountV.btn3.topLB.text = self.personalInfoDic[@"YMoney"];
            
            // 我的积分
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(MyJiFenAction)];
            [accountV.btn1 addGestureRecognizer:tap];
            // 消费总额
            UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(AccountAction)];
            [accountV.btn2 addGestureRecognizer:tap1];
            // 账户余额
            UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(AccountAction)];
            [accountV.btn3 addGestureRecognizer:tap2];
            
        } else if (indexPath.section == 2) {
            UILabel *label1 = [UILabel labelWithText:@"我的订单" textColor:UIColorFromRGB(0x333333) fontSize:15];
            [label1 sizeToFit];
            [cell.contentView addSubview:label1];
            [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(cell.contentView);
                make.left.equalTo(cell.contentView).offset(rateWidth(30));
            }];
            
            UILabel *label2 = [UILabel labelWithText:@"查看全部订单" textColor:mineTextColor fontSize:14];
            [label2 sizeToFit];
            [cell.contentView addSubview:label2];
            [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(cell.contentView);
                make.right.equalTo(cell.contentView).offset(-rateWidth(70));
            }];
            
            UIImageView *arrow = [[UIImageView alloc] init];
            arrow.image = UIImageNamed(@"rightArrow");
            [arrow sizeToFit];
            [cell.contentView addSubview:arrow];
            [arrow mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(cell.contentView).offset(-rateWidth(30));
                make.centerY.equalTo(cell.contentView);
            }];
        } else if (indexPath.section == 3) {
            MineOrderItem *orderItem = [[MineOrderItem alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, rateWidth(180))];
            [cell.contentView addSubview:orderItem];
            orderItem.btn1.tag = 1;
            orderItem.btn2.tag = 2;
            orderItem.btn3.tag = 3;
            orderItem.btn4.tag = 4;
            orderItem.btn5.tag = 5;
            
            [orderItem.btn1 addTarget:self action:@selector(orderAction:) forControlEvents:(UIControlEventTouchUpInside)];
            [orderItem.btn2 addTarget:self action:@selector(orderAction:) forControlEvents:(UIControlEventTouchUpInside)];
            [orderItem.btn3 addTarget:self action:@selector(orderAction:) forControlEvents:(UIControlEventTouchUpInside)];
            [orderItem.btn4 addTarget:self action:@selector(orderAction:) forControlEvents:(UIControlEventTouchUpInside)];
            [orderItem.btn5 addTarget:self action:@selector(orderAction:) forControlEvents:(UIControlEventTouchUpInside)];
            if (self.orderNumDic) {
                if ([[NSString stringWithFormat:@"%@",self.orderNumDic[@"OrderCount1"]] intValue] > 0) {
                    orderItem.redLB1.hidden = NO;
                    orderItem.redLB1.text = [NSString stringWithFormat:@"%@",self.orderNumDic[@"OrderCount1"]];
                }
                if ([[NSString stringWithFormat:@"%@",self.orderNumDic[@"OrderCount2"]] intValue] > 0) {
                    orderItem.redLB2.hidden = NO;
                    orderItem.redLB2.text = [NSString stringWithFormat:@"%@",self.orderNumDic[@"OrderCount2"]];
                }
                if ([[NSString stringWithFormat:@"%@",self.orderNumDic[@"OrderCount3"]] intValue] > 0) {
                    orderItem.redLB3.hidden = NO;
                    orderItem.redLB3.text = [NSString stringWithFormat:@"%@",self.orderNumDic[@"OrderCount3"]];
                }
                if ([[NSString stringWithFormat:@"%@",self.orderNumDic[@"OrderCount4"]] intValue] > 0) {
                    orderItem.redLB4.hidden = NO;
                    orderItem.redLB4.text = [NSString stringWithFormat:@"%@",self.orderNumDic[@"OrderCount4"]];
                }
            }
        }
        cell.selectionStyle = NO;
        return cell;
    }
    
}
- (void)loginAction
{
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    [self presentViewController:loginVC animated:YES completion:nil];
}
#pragma mark - 个人资料
- (void)personalInfoAction
{
    PersonalInfoViewController *personalInfoVC = [[PersonalInfoViewController alloc] init];
    [self.navigationController pushViewController:personalInfoVC animated:YES];
}
#pragma mark - 消费总额
- (void)AccountAction
{
    if ([[UserDefaults valueForKey:@"isLogin"] intValue] == 0) {
        // 未登录
        [self loginAction];
    } else {
        AccountViewController *accountVC = [[AccountViewController alloc] init];
        [self.navigationController pushViewController:accountVC animated:YES];
    }
}
#pragma mark - 我的积分
- (void)MyJiFenAction
{
    if ([[UserDefaults valueForKey:@"isLogin"] intValue] == 0) {
        // 未登录
        [self loginAction];
    } else {
        MyJiFenViewController *myJiFenVC = [[MyJiFenViewController alloc] init];
        [self.navigationController pushViewController:myJiFenVC animated:YES];
    }
}
- (void)orderAction:(UIButton *)btn
{
    if ([[UserDefaults valueForKey:@"isLogin"] intValue] == 0) {
        // 未登录
        [self loginAction];
    } else {
        if (btn.tag == 5) {
            // 退款
            TuiKuanViewController *tuiKuanVC = [[TuiKuanViewController alloc] init];
            [self.navigationController pushViewController:tuiKuanVC animated:YES];
        } else {
            OrderViewController *orderVC = [[OrderViewController alloc] init];
            orderVC.selectIndex1 = btn.tag;
            [self.navigationController pushViewController:orderVC animated:YES];
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return rateWidth(300);
    } else if (indexPath.section == 1) {
        return rateWidth(120);
    } else if (indexPath.section == 2) {
        return rateWidth(70);
    } else if (indexPath.section == 3) {
        return rateWidth(180);
    } else {
        return rateWidth(90);
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 0.01;
    } else if (section == 1 || section == 3) {
        return rateWidth(10);
    } else if (section == 2) {
        return rateWidth(2);
    } else {
        return rateWidth(110);
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 4) {
        UILabel *bgV = [UILabel labelWithText:@"久九科技提供技术支持" textColor:mineTextColor fontSize:10];
        bgV.textAlignment = NSTextAlignmentCenter;
        bgV.backgroundColor = UIColorWhite;
        
        return bgV;
    } else {
        return nil;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2) {
        // 我的订单
        if ([[UserDefaults valueForKey:@"isLogin"] intValue] == 0) {
            // 未登录
            [self loginAction];
        } else {
            OrderViewController *orderVC = [[OrderViewController alloc] init];
            orderVC.selectIndex1 = 0;
            [self.navigationController pushViewController:orderVC animated:YES];
        }
        
    } else if (indexPath.section == 4 && indexPath.row == 7) {
        // 站内通知
        if ([[UserDefaults valueForKey:@"isLogin"] intValue] == 0) {
            // 未登录
            [self loginAction];
        } else {
            NotificationViewController *notificationVC = [[NotificationViewController alloc] init];
            [self.navigationController pushViewController:notificationVC animated:YES];
        }
        
    } else if (indexPath.section == 4 && indexPath.row == 6) {
        // 我的消息
        if ([[UserDefaults valueForKey:@"isLogin"] intValue] == 0) {
            // 未登录
            [self loginAction];
        } else {
            MessageViewController *messageVC = [[MessageViewController alloc] init];
            [self.navigationController pushViewController:messageVC animated:YES];
        }
        
    } else if (indexPath.section == 4 && indexPath.row == 5) {
        // 我的收藏
        if ([[UserDefaults valueForKey:@"isLogin"] intValue] == 0) {
            // 未登录
            [self loginAction];
        } else {
            CollectionViewController *collectionVC = [[CollectionViewController alloc] init];
            [self.navigationController pushViewController:collectionVC animated:YES];
        }
        
    } else if (indexPath.section == 4 && indexPath.row == 4) {
        // 收货地址
        if ([[UserDefaults valueForKey:@"isLogin"] intValue] == 0) {
            // 未登录
            [self loginAction];
        } else {
            AddressViewController *addressVC = [[AddressViewController alloc] init];
            [self.navigationController pushViewController:addressVC animated:YES];
        }
        
    } else if (indexPath.section == 4 && indexPath.row == 3) {
        // 个人资料
        if ([[UserDefaults valueForKey:@"isLogin"] intValue] == 0) {
            // 未登录
            [self loginAction];
        } else {
            PersonalInfoViewController *personalVC = [[PersonalInfoViewController alloc] init];
            [self.navigationController pushViewController:personalVC animated:YES];
        }
        
    } else if (indexPath.section == 4 && indexPath.row == 1) {
        // 优惠券
        if ([[UserDefaults valueForKey:@"isLogin"] intValue] == 0) {
            // 未登录
            [self loginAction];
        } else {
            CouponsViewController *couponsVC = [[CouponsViewController alloc] init];
            [self.navigationController pushViewController:couponsVC animated:YES];
        }
        
    } else if (indexPath.section == 4 && indexPath.row == 2) {
        // 积分订单
        if ([[UserDefaults valueForKey:@"isLogin"] intValue] == 0) {
            // 未登录
            [self loginAction];
        } else {
            JiFenOrderViewController *jiFenOrderVC = [[JiFenOrderViewController alloc] init];
            [self.navigationController pushViewController:jiFenOrderVC animated:YES];
        }
        
    } else if (indexPath.section == 4 && indexPath.row == 0) {
        // 商品评价
        if ([[UserDefaults valueForKey:@"isLogin"] intValue] == 0) {
            // 未登录
            [self loginAction];
        } else {
            MyPingJiaViewController *myPingJiaVC = [[MyPingJiaViewController alloc] init];
            [self.navigationController pushViewController:myPingJiaVC animated:YES];
        }
        
    }
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -TopHeight, kScreenWidth, kScreenHeight+TopHeight-49-SafeAreaBottomHeight) style:(UITableViewStyleGrouped)];
        _tableView.backgroundColor = tableViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.showsVerticalScrollIndicator = NO;
        //        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        WeakSelf
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf getPersonalInfo];
            [weakSelf getOrderNum];
        }];
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
